package vn.ikame.android.boojtran.truyenbua.utility;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public final class StorageUtils {
	private static final String INDIVIDUAL_DIR_NAME = "uil-images";

	public static File getCacheDirectory(Context context) {
		File folderCache = null;
		if (Environment.getExternalStorageState().equals("mounted"))
			folderCache = getExternalCacheDir(context);
		if (folderCache == null)
			folderCache = context.getCacheDir();
		return folderCache;
	}

	// Thư mục tạm ở thẻ nhớ
	private static File getExternalCacheDir(Context paramContext) {
		File sdCard = Environment.getExternalStorageDirectory();
		File folderAndroid = new File(sdCard, "Android");
		File folderData = new File(folderAndroid, "data");
		String str = paramContext.getPackageName();
		File folderPackage = new File(folderData, str);
		File folderCache = new File(folderPackage, "cache");
		if (!folderCache.exists())
			;
		try {
			new File(folderData, ".nomedia").createNewFile();
			if (!folderCache.mkdirs()) {
				Log.w("StorageUtils",
						"Unable to create external cache directory");
				folderCache = null;
			}
			return folderCache;
		} catch (IOException localIOException) {
			Log.w("StorageUtils",
					"Can't create \".nomedia\" file in application external cache directory",
					localIOException);
		}
		return null;
	}

	public static File getIndividualCacheDirectory(Context context) {
		File folderCache = getCacheDirectory(context);
		File folderIndividual = new File(folderCache, INDIVIDUAL_DIR_NAME);
		if ((!folderIndividual.exists()) && (!folderIndividual.mkdir()))
			folderIndividual = folderCache;
		return folderIndividual;
	}

	public static String getNamePic(String photoUrl) {
		// int index = photoUrl.lastIndexOf("/");
		// String fileName = photoUrl.substring(index + 1);
		// return fileName;
		if (photoUrl == null) {
			throw new RuntimeException("Null url passed in");
		} else {
			return photoUrl.replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+",
					"+");
		}
	}

	public static String getPathFileSaveFromUrl(Context context, String photoUrl) {
		String folderCache = String.valueOf(StorageUtils
				.getIndividualCacheDirectory(context).getAbsolutePath());
		String filePath = folderCache + "/" + getNamePic(photoUrl);
		return filePath;
	}

	public static String getPathSaveOfFileList(Context ctx, int index) {
		String path = ctx.getFilesDir().getPath() + "linkData" + index;
		return path;
	}
}
